#include "ShaderObject.h"

//
//	Constructor from string
//
ShaderObject::ShaderObject(string s, GLenum type, bool isFilename) {

	this->type = type;

	// If filename specified, get the contents of the file
	string shader = s;
	if(isFilename) {
		ifstream file(s);
		if(!file.good()) {
			throw runtime_error("COULD NOT OPEN SHADER FILE: " + s);
		}

		shader.clear();
		string temp;
		while(!file.eof()) {
			getline(file, temp);
			shader += temp + "\n";
		}

		file.close();
	}

	// Create a shader from the conents of "shader" string
	try {
		createShaderFromString(shader, type);
	} catch(runtime_error &e) {
		throw runtime_error("COMPILATION ERROR IN SHADER: " + s + "\n" + e.what());
	}
};



//
//	Constructor from fstream
//
ShaderObject::ShaderObject(ifstream &file, GLenum type) {

	if(!file.good()) {
		throw runtime_error("COULD NOT OPEN SHADER FILE.");
	}

	string shader;
	string temp;
	while(!file.eof()) {
		getline(file, temp);
		shader += temp + "\n";
	}

	//file.close();	// should we close this, or leave it up to the caller?
	createShaderFromString(shader, type);
};



//
//	Destructor
//
ShaderObject::~ShaderObject(void) {
	glDeleteShader(id);
};



//
//	Create shader from string
//
void ShaderObject::createShaderFromString(string shader, GLenum type) {
	this->id = glCreateShader(type);

	const char *chars = shader.c_str();
	glShaderSource(id, 1, &chars, NULL);

	glCompileShader(id);

	GLint status;
	glGetShaderiv(id, GL_COMPILE_STATUS, &status);

	// Did the shader compile correctly?
	if(status != GL_TRUE) {
		char error[512];
		glGetInfoLogARB(id, sizeof(error), NULL, error);
		throw runtime_error(error);
	}
};


